from pyevolve import G1DList, Crossovers, Mutators
from pyevolve import GSimpleGA
from pyevolve import Selectors
from pyevolve import Statistics
from pyevolve import DBAdapters
from heuristicas import *
from pyevolve import Initializators, Mutators, Consts
import five_field_kono
from juegos._contests import *
from juegos._agents import RandomAgent, MiniMaxAgent, AlphaBetaAgent
import pyevolve
from five_field_kono import FiveFieldKonoMiniMaxAgent
import sys

rnd = random.Random()

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
    
    heuristica = heuristic_wrap(chromosome)
    
    agenteEvaluador = FiveFieldKonoMiniMaxAgent('MiniMaxAgent_%05d' % 1, 1, rnd,heuristic=heuristica.heuristicaDistanciaDestino)
    agentes = []
    agentes.append(agenteEvaluador)
    agenteContrincante = FiveFieldKonoMiniMaxAgent('MiniMaxAgent_%05d' %2, 0, rnd)
    agentes.append(agenteContrincante)
    
    
    stats = complete(AllAgainstAll_Contest(Five_field_kono(), agentes, 5))

    partidos_jugados = float(stats._stats['matches_played'][agenteEvaluador]) 
    partidos_ganados = float(stats._stats['matches_won'][agenteEvaluador])
    partidos_perdidos = float(stats._stats['matches_lost'][agenteEvaluador]) 
    partidos_empatados = partidos_jugados - (partidos_ganados + partidos_perdidos)
    resultado = (3* partidos_ganados + partidos_empatados ) 
    print str(chromosome.genomeList) + ' - ' +str(resultado) +'. Partidos jugados: '+str(partidos_jugados)+'. Partidos ganados: '+str(partidos_ganados)+'. Jugador: '+agenteEvaluador.player + ' partidos empatados: '+str(partidos_empatados) +' partidos perdidos: '+str(partidos_perdidos)
    return resultado




def run_main():
    genome = G1DList.G1DList(5)
    genome.setParams( rangemin=0, rangemax=50)
    genome.initializator.set(Initializators.G1DListInitializatorInteger)
    genome.mutator.set(Mutators.G1DListMutatorIntegerRange)
    genome.crossover.set(Crossovers.G1DListCrossoverTwoPoint)
    genome.evaluator.set(eval_func)
    
    
    ga = GSimpleGA.GSimpleGA(genome) 
    ga.setMinimax(Consts.minimaxType["maximize"])
    ga.setPopulationSize(6)
    ga.setElitism(True)    
    ga.setGenerations(20)
    ga.setMutationRate(0.02)
    ga.setCrossoverRate(1.0)
    ga.selector.set(Selectors.GRouletteWheel) 
    
    #ga.selector.set(Selectors.GRouletteWheel)
   # This DBAdapter is to create graphs later, it'll store statistics in
   # a SQLite db file
    sqlite_adapter = DBAdapters.DBSQLite(identify="ex1", resetDB=True)
    ga.setDBAdapter(sqlite_adapter)
   
    ga.evolve(freq_stats=1)
 
    best = ga.bestIndividual()
    print best
    print "\nBest individual score: %.2f\n" % (best.score,)

if __name__ == "__main__":
   run_main()
# Enable the pyevolve logging system

pyevolve.logEnable()
# Genome instance, 1D List of 50 elements
#genome = G1DList.G1DList(5)

# Sets the range max and min of the 1D List
#genome.setParams(rangemin=1, rangemax=50)

# The evaluator function (evaluation function)

# Genetic Algorithm Instance



# Set the Roulette Wheel selector method, the number of generations and
# the termination criteria



#ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)


# Sets the DB Adapter, the resetDB flag will make the Adapter recreate
# the database and erase all data every run, you should use this flag
# just in the first time, after the pyevolve.db was created, you can
# omit it.


# Do the evolution, with stats dump
# frequency of 20 generations



  


